package cn.jiangjiesheng.bootstrap.gateway.commons.config;

import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisURI;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by dev@jiangjiesheng.cn on 2022/9/7  <br/>
 *
 * @author dev@jiangjiesheng.cn
 */
@EnableConfigurationProperties(RedisProperties.class)
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, JSONObject> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, JSONObject> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory(RedisProperties redisProperties) {
        final RedisConfiguration redisConfiguration = LettuceConnectionFactory.createRedisConfiguration(RedisURI.builder()
                .withDatabase(redisProperties.getDatabase())
                .withPassword(redisProperties.getPassword())
                .withHost(redisProperties.getHost())
                .withPort(redisProperties.getPort())
                .withSsl(redisProperties.isSsl())
                .build());
        return new LettuceConnectionFactory(redisConfiguration);
    }

    @Bean
    public RedisSerializationContext redisSerializationContext() {
        RedisSerializationContext.RedisSerializationContextBuilder builder = RedisSerializationContext.newSerializationContext();
        builder.key(StringRedisSerializer.UTF_8);
        builder.value(RedisSerializer.json());
        builder.hashKey(StringRedisSerializer.UTF_8);
        builder.hashValue(StringRedisSerializer.UTF_8);
        return builder.build();
    }

//    @Bean
//    public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory) {
//        RedisSerializationContext serializationContext = redisSerializationContext();
//        ReactiveRedisTemplate reactiveRedisTemplate = new ReactiveRedisTemplate(connectionFactory,serializationContext);
//        return reactiveRedisTemplate;
//    }

}
